package com.hx.voice.recognition.auth.client.runner;

import com.hx.voice.recognition.auth.client.config.ServiceAuthConfig;
import com.hx.voice.recognition.auth.client.config.UserAuthConfig;
import com.hx.voice.recognition.auth.client.feign.ServiceAuthFeign;
import com.hx.voice.recognition.common.msg.BaseResponse;
import com.hx.voice.recognition.common.msg.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @descripe：程序一启动，第一时间启动该类
 * @company：南京华讯方舟通讯设备有限公司
 * @author：zhoujinbing
 * @time：2019/6/11 15:22
 * @version：V1.0
 */
@Configuration
@Slf4j
public class AuthClientRunner implements CommandLineRunner {

    @Autowired
    private ServiceAuthConfig serviceAuthConfig;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @Autowired
    private ServiceAuthFeign serviceAuthFeign;

    @Override
    public void run(String... args) throws Exception {

        log.debug("初始化加载用户pubKey");
        try {
            refreshUserPubKey();
        }catch (Exception e)
        {
            log.error("初始化加载用户pubKey失败,1分钟后自动重试!",e);
        }

        log.debug("初始化加载客户pubKey");
        try {
            refreshServicePubKey();
        }catch (Exception e)
        {
            log.error("初始化加载客户pubKey失败,1分钟后自动重试!",e);
        }



    }

    /**
     * @description 获取用户公钥
     * @method  refreshUserPubKey
     * @param  []
     * @return void
     * @date: 2019/6/20 10:52
     * @author:zhoujinbing
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void refreshUserPubKey()
    {
        BaseResponse resp = serviceAuthFeign.getUserPubKey(serviceAuthConfig.getClientId(), serviceAuthConfig.getClientSecret());
        if (resp.getStatus() == HttpStatus.OK.value()) {
            ObjectRestResponse<byte[]> userResponse = (ObjectRestResponse<byte[]>) resp;
            this.userAuthConfig.setPubKeyByte(userResponse.getData());
        }
    }

    /**
     * @description 获取应用公钥
     * @method  refreshServicePubKey
     * @param  []
     * @return void
     * @date: 2019/6/20 10:53
     * @author:zhoujinbing
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void refreshServicePubKey()
    {
        BaseResponse resp = serviceAuthFeign.getServicePubKey(serviceAuthConfig.getClientId(), serviceAuthConfig.getClientSecret());
        if (resp.getStatus() == HttpStatus.OK.value()) {
            ObjectRestResponse<byte[]> userResponse = (ObjectRestResponse<byte[]>) resp;
            this.serviceAuthConfig.setPubKeyByte(userResponse.getData());
        }
    }
}